import moment from 'moment'
import _ from 'lodash'
import { Message } from 'element-ui'
export default {
	data() {
		return {
			calendarDialog: false,
			calendarDateStr: '', // 弹窗对应的日期字符串，'2018-10-10'
			currentDay: 1,
			currentMonth: 1,
			currentYear: 2017,
			currentWeek: 1,
			currenDate: '',
			// 当月日历的数据
			days: [],
			// 当月日历的数据按周拆分存储
			calendarData: [],
			// 日历数据初始化-created赋值
			calendarInitData: {},
			// 初始化设置好的产品的日历需展示的所有数据-created赋值
			productData: [],
			// 日历弹框表单
			calendarDialogForm: {
				price: '',
				timeStart: '',
				timeEnd: '',
				checkAll: false,
				isIndeterminate: false,
				validateWeekdays: ['0', '1', '2', '3', '4', '5', '6']
			},
			calendarDialogFormRules: {
        price: [
          { required: true, message: '请输入门市价' },
          { pattern: /^[0-9]{1,8}([.][0-9]{1,2})?$/, message: '请输入数字，最多保留小数点后两位', trigger: 'blur' }
        ],
				timeStart: [{ required: true, message: '请选择开始日期' }],
				timeEnd: [{ required: true, message: '请选择结束日期' }]
			}
		}
	},
	props: {
		calendarProp: { type: Object },
		calendarSet: { type: Array },
		isPrdDetail: { type: Boolean }
	},
	filters: {
		dateFormat: function(date) {
			if (!date) return ''
			return moment(date).format('YYYY-MM-DD')
		}
	},
	created() {
		// 初始化日历对应的数据
		this.calendarInitData = this.calendarProp

		this.productData = this.calendarSet
		this.initDate()
		this.calendarDialogForm.checkAll = true
	},
	methods: {
		/**
		 * 点击日期弹出日历设置弹框
		 * @param {String} validDate 日期字符串，'2017-10-10'
		 */
		setCalendarDate(weekData) {
			let validDate = weekData.validDate
			if (this.isPrdDetail) {
				return
			}
			this.calendarDateStr = validDate
			// 初始化填充弹框字段
			for (let i = 0; i < this.days.length; i++) {
				if (this.days[i].validDate == validDate) {
					this.calendarDialogForm.price = this.days[i].price
				}
			}
			this.calendarDialogForm.timeStart = weekData.date
			this.calendarDialogForm.timeEnd = weekData.date

			this.calendarDialog = true
		},
		/**
		 * 更多信息-全选
		 * @param  {Number} id 分销商分组id
		 * @return {[type]}    [description]
		 */
		handleCheckAllChange() {
			if (!event.target.checked) {
				this.calendarDialogForm.validateWeekdays = []
			} else {
				this.calendarDialogForm.validateWeekdays = ['0', '1', '2', '3', '4', '5', '6']
			}
			this.calendarDialogForm.isIndeterminate = false
		},
		handleCheckedWeekChange(value) {
			const checkedCount = value.length
			this.calendarDialogForm.checkAll = checkedCount === 7
			this.calendarDialogForm.isIndeterminate = checkedCount > 0 && checkedCount < 7
		},
		/**
		 * 保存日历弹框数据
		 * @return {[type]} [description]
		 */
		calendarDialogSave(formName) {
			var t = this
			this.$refs[formName].validate((valid) => {
				if (valid) {
					let setStartTime = t.calendarDialogForm.timeStart.getTime()
					let setEndTime = t.calendarDialogForm.timeEnd.getTime()
					let during = setEndTime - setStartTime
					let dayNum = Math.ceil(during / 1000 / 3600 / 24) + 1
					// 处理有效期数据
					let start = t.calendarDialogForm.timeStart
					var startTimeDay = start.getDate()
					// 处理有效日期（星期）
					let effectWeekArray = t.calendarDialogForm.validateWeekdays
					let dialogPops = []
					let dialogPop = {}
					let updateFlag = false
					for (let i = 0; i < dayNum; i++) {
						let startime = new Date(start.getFullYear(), start.getMonth(), 1)
						let day = startTimeDay + i
						let dayTime = startime.setDate(day)
						dayTime = new Date(dayTime)
						let weekday = dayTime.getDay()
						// 未选择有效星期，则每天都生效
						if (effectWeekArray.length == 0) {
							updateFlag = false
						}
						// t.calendarDialogForm.isSet = true
						for (let j = 0; j < effectWeekArray.length; j++) {
							if (weekday == effectWeekArray[j]) {
								// 符合星期
								updateFlag = true
								let validDate = t.formatDate(dayTime)
								dialogPop = {
									validDate: validDate,
									price: t.calendarDialogForm.price
								}
								dialogPops.push(dialogPop)
							}
						}
					}
					if (!updateFlag) {
						if (effectWeekArray.length == 0) {
							Message({
								message: '有效星期未勾选，无法保存',
								type: 'error',
								duration: 2 * 1000
							})
							return
						} else {
							Message({
								message: '有效日期内不存在勾选的有效星期，无法保存',
								type: 'error',
								duration: 2 * 1000
							})
							return
						}
					} else {
						t.calendarSaveEmit(dialogPops)
					}
				} else {
					return false
				}
			})
		},
		calendarSaveEmit(dialogPops) {
			this.$emit('calendarUpdate', dialogPops)
			this.calendarDialog = false
		},
		/**
		 * 重置日历弹框表单校验提示
		 * @param  {[type]} formName [description]
		 * @return {[type]}          [description]
		 */
		resetForm(formName) {
			this.$refs[formName].resetFields()
			this.calendarDialog = false
		},
		/**
		 * 恢复默认设置
		 */
		resetDefaultSet() {
			var t = this
			let calendarDataReset = {
				data: []
			}
			let info = '本操作将清除 ' + this.formatDate(t.calendarDialogForm.timeStart) + '至' + this.formatDate(t.calendarDialogForm.timeEnd) + '的日历价格设置并启用默认的设置，确认继续？'
			this.$confirm(info, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				let startDate = moment(t.calendarDialogForm.timeStart).startOf('day')
				let lastDate = moment(t.calendarDialogForm.timeEnd).startOf('day')
				let currDate = startDate.clone()
				let dayNum = lastDate.diff(startDate, 'days')
				let effectWeekArray = t.calendarDialogForm.validateWeekdays
				for (let i = 0; i <= dayNum; i++) {
					// 有效日期和有效星期取交集
					if (effectWeekArray.indexOf(currDate.day() + '') != -1) {
						calendarDataReset.data.push(moment(currDate).format('YYYY-MM-DD'))
					}
					currDate.add(1, 'days')
				}

				t.$emit('resetUpdate', calendarDataReset)
				this.calendarDialog = false
			})
		},
		/**
		 * 初始化日历
		 * @param  {DateString} curMonth 要初始化的月份，格式化的日期字符串
		 * @return {[type]}          [description]
		 */
		initDate: function(curMonth) {
			// 清空日历数据
			this.days.length = 0
			let date
			if (curMonth) {
				date = new Date(curMonth)
			} else {
				date = new Date()
				curMonth = this.formatDate(date)
			}
			// 获取初始日期的年月日
			this.currentYear = date.getFullYear()
			this.currentMonth = date.getMonth() + 1
			this.currentDay = date.getDate()

			// 获得初始化月份1号
			var monthFirst = new Date(this.currentYear, this.currentMonth - 1, 1)
			// 获得初始化月份1号对应周几
			this.currentWeek = monthFirst.getDay() // 1...6,0

			// 第一周-当月1号之前
			for (let i = this.currentWeek; i > 0; i--) {
				const index = -(i - 1)
				const eDate = new Date(curMonth).setDate(index)
				this.fillDaysArray(eDate)
			}

			// 当月
			// 获取初始化月天数,注：月份不需要-1
			var dayCount = new Date(this.currentYear, this.currentMonth, 0).getDate()
			for (let j = 1; j <= dayCount; j++) {
				const eDate = new Date(curMonth).setDate(j)
				this.fillDaysArray(eDate)
			}

			// 当月结束后一周内剩下的部分-填充下一周数据
			// 获得初始化月份最后一天
			const monthLast = new Date(this.currentYear, this.currentMonth, 0)
			// 获得初始化月份最后一天对应周几
			const weekofLast = monthLast.getDay()

			// 最后一周-当月最后一天之后
			for (let k = 1; k < (7 - weekofLast); k++) {
				const index = dayCount + k
				const eDate = new Date(curMonth).setDate(index)
				this.fillDaysArray(eDate)
			}
			this.fillDaysAmount()
		},
		/**
		 * 将日期信息填充到days中
		 * @param  {Number} date 填充的日期的毫秒数
		 * @return {[type]}      [description]
		 */
		fillDaysArray(date) {
			const eDate = new Date(date)
			const eDay = eDate.getDate()
			const eDateStr = this.formatDate(eDate)
			const dayObject = {
				date: eDate, // 标准时间
				day: eDay, // 周几
				validDate: eDateStr, // 2017-10-10
				isDisabled: false,
				price: null
			}
			// 判断是否是今日
			if (dayObject.date.getFullYear() == new Date().getFullYear() && dayObject.date.getMonth() == new Date().getMonth() && dayObject.date.getDate() == new Date().getDate()) {
				dayObject.todayClass = true
			}
			const effectTimeStart = this.calendarInitData.effect_time_start.getTime()
			// 判断当前日期是否在有效日期范围内
			if (eDate.getTime() < effectTimeStart) {
				// 不在，则增加属性
				dayObject.isDisabled = true
			}
			this.days.push(dayObject)
		},
		/**
		 * 填充当月的各金额
		 * @param {Array} dateArray this.days 当月的数据
		 * @return {[type]} [description]
		 */
		fillDaysAmount() {
			const dateArray = this.days
			for (let i = 0; i < dateArray.length; i++) {
				const cDate = dateArray[i].validDate
				// 将所有数据设置成批量初始化的数据
				this.days[i].price = this.calendarInitData.price
				// 再遍历单独设置的数据
				for (let j = 0; j < this.productData.length; j++) {
					if (this.productData[j].validDate == cDate) {
						this.days[i].alonePriceClass = true
						this.days[i].price = this.productData[j].price
					}
				}
			}
			this.fillCalendarArray()
		},

		/**
		 * 将当月日期按周存储
		 * @return {[type]} [description]
		 */
		fillCalendarArray() {
			const data = this.days
			const weeks = Math.round(data.length / 7)
			this.calendarData.length = 0
			for (let i = 0; i < weeks; i++) {
				var weekArray = []
				for (let j = 0; j < 7; j++) {
					const date = data[7 * i + j]
					const calendarObject = {
						weekIndex: i,
						weekData: date
					}
					weekArray.push(calendarObject)
				}
				this.calendarData.push(weekArray)
			}
		},

		/**
		 * 日期格式化
		 * @param  {Date} time   标准时间
		 * @return {[type]}      [description]
		 */
		formatDate(time) {
			const y = time.getFullYear()
			let m = time.getMonth() + 1
			let d = time.getDate()
			m < 10 ? m = '0' + m : m
			d < 10 ? d = '0' + d : d
			return y + '-' + m + '-' + d
		},
		prevMonth() {
			let pMonth = this.currentMonth - 1
			let pYear = this.currentYear
			if (pMonth == 0) {
				pMonth = 12
				pYear = this.currentYear - 1
			}
			if (pMonth > 0 && pMonth < 10) {
				pMonth = '0' + pMonth
			}
			const prevDate = pYear + '-' + pMonth

			// 获取有效日期
			const effectYear = this.calendarInitData.effect_time_start.getFullYear()
			let effectMonth = this.calendarInitData.effect_time_start.getMonth()
			if (effectMonth < 10) {
				effectMonth = '0' + effectMonth
			}
			const newdate = effectYear + '-' + effectMonth
			const effectTime = new Date(newdate).getTime()
			const prevMonthTime = new Date(prevDate).getTime()
			if (prevMonthTime > effectTime) {
				this.currenDate = prevDate
				this.initDate(prevDate)
			}
		},
		nextMonth() {
			let nMonth = this.currentMonth + 1
			let nYear = this.currentYear
			if (nMonth == 13) {
				nMonth = 1
				nYear = this.currentYear + 1
			}
			if (nMonth < 10) {
				nMonth = '0' + nMonth
			}
			const nextDate = nYear + '-' + nMonth
			this.initDate(nextDate)
		}
	}
}
